
var Public = Public || {};
var Business = Business || {};
Public.isIE6 = !window.XMLHttpRequest;	//ie6
/* 编码*/
Public.encodeURI=function(value){
	return encodeURI(encodeURI(value));
};
//设置表格宽高
Public.setGrid = function(adjustH, adjustW){
	var adjustH = adjustH || 65;
	var adjustW = adjustW || 20;
	var gridW = $(window).width() - adjustW, gridH = $(window).height() - $(".grid-wrap").offset().top - adjustH;
	return {
		w : gridW,
		h : gridH
	};
};
//重设表格宽高
Public.resizeGrid = function(adjustH, adjustW){
	var grid = $("#grid");
	var gridWH = Public.setGrid(adjustH, adjustW);
	grid.jqGrid('setGridHeight', gridWH.h);
	grid.jqGrid('setGridWidth', gridWH.w);
};
//重设表格宽高
Public.resizeSpecifyGrid = function(gridId, adjustH, adjustW){
	var grid = $("#" + gridId);
	var gridWH = Public.setGrid(adjustH, adjustW);
	grid.jqGrid('setGridHeight', gridWH.h);
	grid.jqGrid('setGridWidth', gridWH.w);
};
//自定义报表宽度初始化以及自适应
Public.initCustomGrid = function(tableObj){
	//去除报表原始定义的宽度
	$(tableObj).css("width") && $(tableObj).attr("width","auto");
	//获取报表宽度当做最小宽度
	var _minWidth = $(tableObj).outerWidth();
	$(tableObj).css("min-width",_minWidth+"px");
	//获取当前window对象的宽度作为报表原始的宽度
	$(tableObj).width($(window).width() - 74);
	//设置resize事件
	var _throttle = function(method,context){
		clearTimeout(method.tid);
		method.tid = setTimeout(function(){
			method.call(context);
		},100);
	};
	var _resize = function(){
		$(tableObj).width($(window).width() - 74);
	};
	$(window).resize(function() {
		_throttle(_resize);
	});
};

//过滤空字段
Public.nullFormatter = function(cellvalue, options, rowObject) {
    if(cellvalue === undefined || cellvalue === 'null' || cellvalue === 'NULL') {
        cellvalue = '';
    }

    return cellvalue;
};
//操作项格式化，适用于有“修改、删除”操作的表格
Public.operFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i> <i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
	html_con += '</div>';
	return html_con;
};

//操作项格式化，适用于有“修改”操作的表格
Public.operEditFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<span class="ui-icon ui-icon-pencil" title="修改">&#xe60c;</span>';
	html_con += '</div>';
	return html_con;
};
Public.operDelFmatter = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
	html_con += '<i class="iconfont ui-icon-trash" title="删除">&#xe60e;</i>';
	html_con += '</div>';
	return html_con;
};
Public.hideConstion = function(){
	$('.ui-btn-menu').each(function(){
		var menu = $(this);
		if($('.con',menu).is(':visible')){
			menu.removeClass('ui-btn-menu-cur');
		}
	});
}

Public.billsOper = function (val, opt, row) {
	var html_con = '<div class="operating" data-id="' + opt.rowId + '"><span class="ui-icon ui-icon-plus" title="新增行"></span><span class="ui-icon ui-icon-trash" title="删除行"></span></div>';
	return html_con;
}

Public.dateCheck = function(){
	$('.ui-datepicker-input').bind('focus', function(e){
		$(this).data('original', $(this).val());
	}).bind('blur', function(e){
		var reg = /((^((1[8-9]\d{2})|([2-9]\d{3}))(-)(10|12|0?[13578])(-)(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(11|0?[469])(-)(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(0?2)(-)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)(-)(0?2)(-)(29)$)|(^([3579][26]00)(-)(0?2)(-)(29)$)|(^([1][89][0][48])(-)(0?2)(-)(29)$)|(^([2-9][0-9][0][48])(-)(0?2)(-)(29)$)|(^([1][89][2468][048])(-)(0?2)(-)(29)$)|(^([2-9][0-9][2468][048])(-)(0?2)(-)(29)$)|(^([1][89][13579][26])(-)(0?2)(-)(29)$)|(^([2-9][0-9][13579][26])(-)(0?2)(-)(29)$))/;
		var _self = $(this);
		setTimeout(function(){
			if(!reg.test(_self.val())) {
				parent.Public.tips({type:1, content : '日期格式有误！如：2013-08-08。'});
				_self.val(_self.data('original'));
			};
		}, 10)

	});
};

//根据之前的编码生成下一个编码
Public.getSuggestNum = function(prevNum){
	if (prevNum == '' || !prevNum) {
		return '';
	}
	var reg = /^([a-zA-Z0-9\-_]*[a-zA-Z\-_]+)?(\d+)$/;
	var match = prevNum.match(reg);
	if (match) {
		var prefix = match[1] || '';
		var prevNum = match[2];
		var num = parseInt(prevNum, 10) + 1;
		var delta = prevNum.toString().length - num.toString().length;
		if (delta > 0) {
			for (var i = 0; i < delta; i++) {
				num = '0' + num;
			}
		}
		return prefix + num;
	} else {
		return '';
	}
};

Public.bindBuySkip = function(obj, func){
	var args = arguments;
	$(obj).on('keydown', 'input:visible:not(:disabled)', function(e){
		if (e.keyCode == '13') {
			var inputs = $(obj).find('input:visible:not(:disabled)');
			var idx = inputs.index($(this));
			idx = idx + 1;
			if (idx >= inputs.length) {
				if (typeof func == 'function') {
					var _args = Array.prototype.slice.call(args, 2 );
					func.apply(null,_args);
				}
			} else {
				inputs.eq(idx).focus();
			}
		}
	});
};

/*获取URL参数值*/
Public.getRequest = Public.urlParam = function() {
   var param, url = location.search, theRequest = {};
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0, len = strs.length; i < len; i ++) {
		 param = strs[i].split("=");
         theRequest[param[0]]=decodeURIComponent(param[1]);
      }
   }
   return theRequest;
};
/*
  通用post请求，返回json
  url:请求地址， params：传递的参数{...}， callback：请求成功回调
*/ 
Public.ajaxPost = function(url, params, callback){    
	$.ajax({  
	   type: "POST",
	   url: url,
	   data: params, 
	   dataType: "json",  
	   success: function(data, status){  
		   callback(data);  
	   },  
	   error: function(err){  
			Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
	   }  
	});  
};  
Public.ajaxGet = function(url, params, callback){    
	$.ajax({  
	   type: "GET",
	   url: url,
	   dataType: "json",  
	   data: params,    
	   success: function(data, status){  
		   callback(data);  
	   },   
	   error: function(err){  
			Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
	   }  
	});  
};
/*操作提示*/
Public.tips = function(options){ return new Public.Tips(options); }
Public.Tips = function(options){
	var defaults = {
		renderTo: 'body',
		type : 0,
		autoClose : true,
		removeOthers : true,
		time : undefined,
		top : 15,
		onClose : null,
		onShow : null
	}
	this.options = $.extend({},defaults,options);
	this._init();
	
	!Public.Tips._collection ?  Public.Tips._collection = [this] : Public.Tips._collection.push(this);
	
}

Public.Tips.removeAll = function(){
	try {
		for(var i=Public.Tips._collection.length-1; i>=0; i--){
			Public.Tips._collection[i].remove();
		}
	}catch(e){}
}

Public.Tips.prototype = {
	_init : function(){
		var self = this,opts = this.options,time;
		if(opts.removeOthers){
			Public.Tips.removeAll();
		}

		this._create();

		this.closeBtn.bind('click',function(){
			self.remove();
		});

		if(opts.autoClose){
			time = opts.time || opts.type == 1 ? 5000 : 3000;
			window.setTimeout(function(){
				self.remove();
			},time);
		}

	},
	
	_create : function(){
		var opts = this.options;
		this.obj = $('<div class="ui-tips"><i></i><span class="close"></span></div>').append(opts.content);
		this.closeBtn = this.obj.find('.close');
		
		switch(opts.type){
			case 0 : 
				this.obj.addClass('ui-tips-success');
				break ;
			case 1 : 
				this.obj.addClass('ui-tips-error');
				break ;
			case 2 : 
				this.obj.addClass('ui-tips-warning');
				break ;
			default :
				this.obj.addClass('ui-tips-success');
				break ;
		}
		
		this.obj.appendTo('body').hide();
		this._setPos();
		if(opts.onShow){
				opts.onShow();
		}

	},

	_setPos : function(){
		var self = this, opts = this.options;
		if(opts.width){
			this.obj.css('width',opts.width);
		}
		var h =  this.obj.outerHeight(),winH = $(window).height(),scrollTop = $(window).scrollTop();
		//var top = parseInt(opts.top) ? (parseInt(opts.top) + scrollTop) : (winH > h ? scrollTop+(winH - h)/2 : scrollTop);
		var top = parseInt(opts.top) + scrollTop;
		this.obj.css({
			position : Public.isIE6 ? 'absolute' : 'fixed',
			left : '50%',
			top : top,
			zIndex : '9999',
			marginLeft : -self.obj.outerWidth()/2	
		});

		window.setTimeout(function(){
			self.obj.show().css({
				marginLeft : -self.obj.outerWidth()/2
			});
		},150);

		if(Public.isIE6){
			$(window).bind('resize scroll',function(){
				var top = $(window).scrollTop() + parseInt(opts.top);
				self.obj.css('top',top);
			})
		}
	},

	remove : function(){
		var opts = this.options;
		this.obj.fadeOut(200,function(){
			$(this).remove();
			if(opts.onClose){
				opts.onClose();
			}
		});
	}
};
//数值显示格式转化
Public.numToCurrency = function(val, dec) {
	val = parseFloat(val);	
	dec = dec || 2;	//小数位
	if(val === 0 || isNaN(val)){
		return '';
	}
	val = val.toFixed(dec).split('.');
	var reg = /(\d{1,3})(?=(\d{3})+(?:$|\D))/g;
	return val[0].replace(reg, "$1,") + '.' + val[1];
};
//数值显示
Public.currencyToNum = function(val){
	var val = String(val);
	if ($.trim(val) == '') {
		return 0;
	}
	val = val.replace(/,/g, '');
	val = parseFloat(val);
	return isNaN(val) ? 0 : val;
};
//只允许输入数字
Public.numerical = function(e){
	var allowed = '0123456789.-', allowedReg;
	allowed = allowed.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
	allowedReg = new RegExp('[' + allowed + ']');
	var charCode = typeof e.charCode != 'undefined' ? e.charCode : e.keyCode; 
	var keyChar = String.fromCharCode(charCode);
	if(!e.ctrlKey && charCode != 0 && ! allowedReg.test(keyChar)){
		e.preventDefault();
	};
};
Public.subLenString = function(str,len){
	if(len != undefined && len != null && len > 0){
		if(str.length > len){
			str = str.substring(0,len) + "...";
		}
	}else{
		len = 8;
		if(str.length > len){
			str = str.substring(0,len) + "...";
		}
	}
	return str;
}
//限制只能输入允许的字符，不支持中文的控制
Public.limitInput = function(obj, allowedReg){
    var ctrlKey = null;
    obj.css('ime-mode', 'disabled').on('keydown',function(e){
        ctrlKey = e.ctrlKey;
    }).on('keypress',function(e){
        allowedReg = typeof allowedReg == 'string' ? new RegExp(allowedReg) : allowedReg;
        var charCode = typeof e.charCode != 'undefined' ? e.charCode : e.keyCode; 
        var keyChar = $.trim(String.fromCharCode(charCode));
        if(!ctrlKey && charCode != 0 && charCode != 13 && !allowedReg.test(keyChar)){
            e.preventDefault();
        } 
    });
};

/*批量绑定页签打开*/
Public.pageTab = function() {
	$(document).on('click', '[rel=pageTab]', function(e){
		e.preventDefault();
		var right = $(this).data('right');
		if (right && !Business.verifyRight(right)) {
			return false;
		};
		var tabid = $(this).attr('tabid'), url = $(this).attr('href'), showClose = $(this).attr('showClose'), text = $(this).attr('tabTxt') || $(this).text(),parentOpen = $(this).attr('parentOpen');
		if(parentOpen){
			parent.tab.addTabItem({tabid: tabid, text: text, url: url, showClose: showClose});
		} else {
			tab.addTabItem({tabid: tabid, text: text, url: url, showClose: showClose});
		}
	});
};

$.fn.artTab = function(options) {
  var defaults = {};
  var opts = $.extend({}, defaults, options);
  var callback = opts.callback || function () {};
  this.each(function(){
	  var $tab_a =$("dt>a",this);
	  var $this = $(this);
	  $tab_a.bind("click", function(){
		  var target = $(this);
		  target.siblings().removeClass("cur").end().addClass("cur");
		  var index = $tab_a.index(this);
		  var showContent = $("dd>div", $this).eq(index);
		  showContent.siblings().hide().end().show();
		  callback(target, showContent, opts);
	  });
	  if(opts.tab)
		  $tab_a.eq(opts.tab).trigger("click");
	  if(location.hash) {
		  var tabs = location.hash.substr(1);
		  $tab_a.eq(tabs).trigger("click");
	  }
  });	  
};

//文本列表滚动
Public.txtSlide = function(opt){
	var def = {
		notice: '#notices > ul',
		size: 1, //显示出来的条数
		pause_time: 3000, //每次滚动后停留的时间
		speed: 'normal', //滚动动画执行的时间
		stop: true //鼠标移到列表时停止动画
	};
	opt = opt || {};
	opt = $.extend({}, def, opt);

	var $list = $(opt.notice),
		$lis = $list.children(),
		height = $lis.eq(0).outerHeight() * opt.size,
		interval_id;
	if($lis.length <= opt.size) return;
	interval_id = setInterval(begin, opt.pause_time);
	opt.stop && $list.on({
		'mouseover': function(){
			clearInterval(interval_id);
			$list.stop(true,true);
		},
		'mouseleave': function(){
			interval_id = setInterval(begin, opt.pause_time);
		}
	});

	function begin(){
		$list.stop(true, true).animate({marginTop: -height}, opt.speed, function(){
			for(var i=0; i<opt.size; i++){
				$list.append($list.find('li:first'));
			}
			$list.css('margin-top', 0);
		});
	}
};

$.fn.enterKey = function() {
	this.each(function() {
		$(this).keydown(function(e) {
			if (e.which == 13) {
				var ref = $(this).data("ref");
				if (ref) {
					$('#' + ref).select().focus().click();
				}
				else {
					eval($(this).data("enterKeyHandler"));
				}
			}
		});
	});
};


//input占位符
$.fn.placeholder = function(){
	this.each(function() {
		$(this).focus(function(){
			if($.trim(this.value) == this.defaultValue){
				this.value = '';
			}
			$(this).removeClass('ui-input-ph');
		}).blur(function(){
			var val = $.trim(this.value);
			if(val == '' || val == this.defaultValue){
				$(this).addClass('ui-input-ph');
			}
			val == '' && $(this).val(this.defaultValue);
		});
	});
};

//单选框插件
$.fn.cssRadio = function(opts){
	var opts = $.extend({}, opts);
	var $_radio = $('label.radio', this), $_this = this;
	$_radio.each(function() {
		var self = $(this);
		if (self.find("input")[0].checked) {
			self.addClass("checked");
		};
	}).hover(function() {
		$(this).addClass("over");
	}, function() {
		$(this).removeClass("over");
	}).click(function(event) {
		$_radio.find("input").removeAttr("checked");
		$_radio.removeClass("checked");
		$(this).find("input").attr("checked", "checked");
		$(this).addClass("checked");
		opts.callback($(this));
	});
	return {
		getValue: function() {
			return $_radio.find("input[checked]").val();
		},
		setValue: function(index) {
			return $_radio.eq(index).click();
		}
	}
};

//复选框插件
$.fn.cssCheckbox = function(opts) {
    if (opts) {
        opts = $.extend({}, opts);
    }
	var $_chk = $(".chk", this);
	$_chk.each(function() {
		if ($(this).find("input")[0].checked) {
			$(this).addClass("checked");
		};
		if ($(this).find("input")[0].disabled) {
			$(this).addClass("dis_check");
		};
	}).hover(function() {
		$(this).addClass("over")
	}, function() {
		$(this).removeClass("over")
	}).click(function(event) {
		if ($(this).find("input")[0].disabled) {
			return;
		};
		$(this).toggleClass("checked");
		$(this).find("input")[0].checked = !$(this).find("input")[0].checked;
        if (opts) {
            opts.callback($(this));
        }
		event.preventDefault();
	});
	
	return {
		chkAll:function(){
			$_chk.addClass("checked");
//			$_chk.find("input").attr("checked","checked");
			$_chk.find("input").prop("checked",true);
		},	
		chkNot:function(){
			$_chk.removeClass("checked");
//			$_chk.find("input").removeAttr("checked");
			$_chk.find("input").prop("checked",false);
		},
		chkVal:function(){
			var val = [];
			$_chk.find("input:checked").each(function() {
            	val.push($(this).val());
        	});
			return val;
		}
	}
};

Public.getDefaultPage = function(){
	var win = window.self;
	do{
		if (win.SYSTEM) {
			return win;
		}
		win = win.parent;
	} while(true);
};

//权限验证
Business.verifyRight = function(limitMenu,menuParam){
	var config = Public.getDefaultPage().CONFIG;
	var limit = config.OPTIONLIMIT;
	if(limitMenu != undefined && limitMenu != ''){
		if(menuParam == limit.INSERT){ //新增
			if(limitMenu.indexOf(limit.INSERT) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.UPDATE){ //修改
			if(limitMenu.indexOf(limit.UPDATE) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.DELETE){ //删除
			if(limitMenu.indexOf(limit.DELETE) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.SELECT){ //查询
			if(limitMenu.indexOf(limit.SELECT) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.EXPORT){ //导出
			if(limitMenu.indexOf(limit.EXPORT) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.APPROVE){ //审批
			if(limitMenu.indexOf(limit.APPROVE) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.BACK){ //反审批
			if(limitMenu.indexOf(limit.BACK) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.FINISH){ //终止
			if(limitMenu.indexOf(limit.FINISH) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.PRINT){ //打印
			if(limitMenu.indexOf(limit.PRINT) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else if(menuParam == limit.IMPORT){ //导入
			if(limitMenu.indexOf(limit.IMPORT) > -1){
				return true;
			}else{
				Business.alert();
				return false;
			}
		}else{
			Business.alert();
			return false;
		}
	}else{
		Business.alert();
		return false;
	}
};

Business.verifyRightValue = function(limitMenu,menuParam){
	var config = Public.getDefaultPage().CONFIG;
	var limit = config.OPTIONLIMIT;
	if(limitMenu != undefined && limitMenu != ''){
		if(menuParam == limit.INSERT){ //新增
			if(limitMenu.indexOf(limit.INSERT) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.UPDATE){ //修改
			if(limitMenu.indexOf(limit.UPDATE) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.DELETE){ //删除
			if(limitMenu.indexOf(limit.DELETE) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.SELECT){ //查询
			if(limitMenu.indexOf(limit.SELECT) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.EXPORT){ //导出
			if(limitMenu.indexOf(limit.EXPORT) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.APPROVE){ //审批
			if(limitMenu.indexOf(limit.APPROVE) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.BACK){ //审批
			if(limitMenu.indexOf(limit.BACK) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.FINISH){ //终止
			if(limitMenu.indexOf(limit.FINISH) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.PRINT){ //打印
			if(limitMenu.indexOf(limit.PRINT) > -1){
				return true;
			}else{
				return false;
			}
		}else if(menuParam == limit.IMPORT){ //导入
			if(limitMenu.indexOf(limit.IMPORT) > -1){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}else{
		return false;
	}
};
PriceLimit = {
	config : Public.getDefaultPage().CONFIG,
	system : Public.getDefaultPage().SYSTEM,
	hasEnter : function(){
		return system.PRICELIMIT.indexOf(config.PRICELIMIT.ENTER) > -1;
	},
	hasCost : function(){
		return system.PRICELIMIT.indexOf(config.PRICELIMIT.COST) > -1;
	},
	hasBatch : function(){
		return system.PRICELIMIT.indexOf(config.PRICELIMIT.BATCH) > -1;
	},
	hasSell : function(){
		return system.PRICELIMIT.indexOf(config.PRICELIMIT.SELL) > -1;
	},
	hasDistribute : function(){
		return system.PRICELIMIT.indexOf(config.PRICELIMIT.DISTRIBUTE) > -1;
	},
	formatMoney:function(value){
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		return parseFloat(value).toFixed(2); 
	},
	formatByEnter:function(value){//进货价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.ENTER) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatBySell:function(value){//零售价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.SELL) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByCost:function(value){//成本价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.COST) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByDistribute:function(value){//配送价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.DISTRIBUTE) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByVip:function(value){//会员价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.VIP) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByBatch:function(value){//批发价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.BATCH) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByProfit:function(value){//利润
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.PROFIT) > -1) {
			return parseFloat(value).toFixed(2);
		}
		return "***";
	},
	formatByEnter_Sell:function(value){//进货价&零售价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.ENTER) == -1) {
			return "***";
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.SELL) == -1) {
			return "***";
		}
		return parseFloat(value).toFixed(2);
	},
	formatByBatch_Sell:function(value){//批发价&零售价
		if($.trim(value) == '' || isNaN(value)){
			return '';
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.BATCH) == -1) {
			return "***";
		}
		if (system.PRICELIMIT.indexOf(config.PRICELIMIT.SELL) == -1) {
			return "***";
		}
		return parseFloat(value).toFixed(2);
	}
}

Business.alert = function(){
	var html = [
		'<div class="ui-dialog-tips">',
		'<h4 class="tit">您没有该功能的使用权限哦！</h4>',
		'<p>请联系管理员为您授权！</p>',
		'</div>'
	].join('');
	$.dialog({
		width: 240,
		title: '系统提示',
		icon: 'alert.gif',
		fixed: true,
		lock: true,
		resize: false,
		ok: true,
		content: html
	});
}


//获取文件
Business.getFile = function(url, args, isNewWinOpen){
	if (typeof url != 'string') {
		return ;
	}
	var url = url.indexOf('?') == -1 ? url += '?' : url;
	url += '&random=' + new Date().getTime();
	var downloadForm = $('form#downloadForm');
	if (downloadForm.length == 0) {
		downloadForm = $('<form method="post" />').attr('id', 'downloadForm').hide().appendTo('body');
	} else {
		downloadForm.empty();
	}
	downloadForm.attr('action', url);
	for( k in args){
		$('<input type="hidden" />').attr({name: k, value: args[k]}).appendTo(downloadForm);
	}
	if (isNewWinOpen) {
		downloadForm.attr('target', '_blank');
	} else{
		var downloadIframe = $('iframe#downloadIframe');
		if (downloadIframe.length == 0) {
			downloadIframe = $('<iframe />').attr('id', 'downloadIframe').hide().appendTo('body');
		}
		downloadForm.attr('target', 'downloadIframe');
	}
	downloadForm.trigger('submit');
};

//将弹窗中返回的数据记录到相应的input中
Business.setFilterData = function(dialogCtn, $input){
	var ids = dialogCtn.$("#grid").jqGrid('getGridParam', 'selarrrow'), 
		len = ids.length,
		numbers = [];
	if(len > 0){
		$.each(ids, function(idx, val){
			var row = dialogCtn.$("#grid").jqGrid('getRowData', val);
			numbers.push(row.number || row.locationNo);
		});
		$input.data('ids', ids.join(',')).val(numbers.join(','));
	}
};

Business.setFilterGoods = function(dialogCtn, $input){
	var ids = dialogCtn.$("#grid").jqGrid('getGridParam', 'selarrrow'), 
		len = ids.length,
		numbers = [];
	if($.trim($input.val()) !== '') {
		numbers.push($input.val());
	};
	if(len > 0){
		$.each(ids, function(idx, val){
			var row = dialogCtn.$("#grid").jqGrid('getRowData', val);
			numbers.push(row.number);
		});
		$input.data('ids', numbers.join(',')).val(numbers.join(','));
	}
};

Business.moreFilterEvent = function(){
	$('#conditions-trigger').on('click', function(e){
		e.preventDefault();
	  if (!$(this).hasClass('conditions-expand')) {
		  $('#more-conditions').stop().slideDown(200, function(){
			   $('#conditions-trigger').addClass('conditions-expand').html('收起更多<b></b>');
			   $('#filter-reset').css('display', 'inline');
		  });
	  } else {
		  $('#more-conditions').stop().slideUp(200, function(){
			  $('#conditions-trigger').removeClass('conditions-expand').html('更多条件<b></b>');
			  $('#filter-reset').css('display', 'none');
		  });
	  };
	});
};

Business.gridEvent = function(){
	$('.grid-wrap').on('mouseenter', '.list tbody tr', function(e){
		$(this).addClass('tr-hover');
		if($_curTr) {
			$_curTr.removeClass('tr-hover');
			$_curTr = null;
		}
	}).on('mouseleave', '.list tbody tr', function(e){
		$(this).removeClass('tr-hover');
	});
};

//判断:当前元素是否是被筛选元素的子元素
$.fn.isChildOf = function(b){
    return (this.parents(b).length > 0);
};

//判断:当前元素是否是被筛选元素的子元素或者本身
$.fn.isChildAndSelfOf = function(b){
    return (this.closest(b).length > 0);
};

//数字输入框
$.fn.digital = function() {
	this.each(function(){
		$(this).keyup(function() {
			this.value = this.value.replace(/\D/g,'');
		})
	});
};
/** 
 1. 设置cookie的值，把name变量的值设为value   
example $.cookie(’name’, ‘value’);
 2.新建一个cookie 包括有效期 路径 域名等
example $.cookie(’name’, ‘value’, {expires: 7, path: ‘/’, domain: ‘jquery.com’, secure: true});
3.新建cookie
example $.cookie(’name’, ‘value’);
4.删除一个cookie
example $.cookie(’name’, null);
5.取一个cookie(name)值给myvar
var account= $.cookie('name');
**/
$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
function doChangeValue(id){
	if(id != undefined && id != null && id != ""){
		$("#"+id).val("");
	}else{
		return;
	}
}
function doFocus(id){
	if(id != undefined && id != null && id != ""){
		$("#"+id).focus();
	}else{
		return;
	}
}

var mobileRegx = /^1[3|4|5|7|8][0-9]{9}$/ ;//手机号正则
var phoneRegx =/^((0[0-9]{2,3})-)([0-9]{7,8})(-([0-9]{3,}))?$/; //电话号码正则
/**校验手机号码或者电话**/
function checkTelORMoblie(tel) 
{ 
   return mobileRegx.test(tel) || phoneRegx.test(tel);
}
/**校验手机号码**/
function isMobilePhone(mobilePhone)
{
	return mobileRegx.test(mobilePhone);
}
/**校验电话号码**/
function isTelePhone(telePhone)
{
	return phoneRegx.test(telePhone);
}
/**校验QQ号码**/
function checkQQ(QQ){
	var qq = /^[1-9]{1}[0-9]{4,10}$/;
	return qq.test(QQ);
}
checkImportDate = function(sysdate){
	var hour = sysdate.substring(11,13);
	if(undefined != hour && "" != hour){
		if(parseInt(hour)<21 && parseInt(hour) >= 10){
			$.dialog.tips("10-21时不能导入大于300K!",2,"32X32/fail.png");
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}
/**去掉日期后面的.0*/
function date(val, opt, row){
	var dateS=val.substring(0,val.length-2);
	return dateS;
}
/**检查单个，多选框是否选中，并且改变对应值
 * name 多选框name值
 * checkedVal 选中值
 * noCheckedVal 没有选中值
 * */
function checkBoxValidate(name,checkedVal,noCheckedVal){ 
  if($("input[name="+name+"]").attr("checked")=='checked'){//选中
     $("#"+name).val(checkedVal);
  }else{
     $("#"+name).val(noCheckedVal);
  }
}


function onlyDoubleNumber(obj,event,canNegative){
	var keyCode = event.keyCode||event.which;
	if(keyCode == 8 || keyCode == 9 || keyCode == 37 || keyCode == 39){//退格键、tab键、左右方向键
		return;
	}
	if(canNegative != undefined && canNegative){//可以输入负数
		if(!(((keyCode >= 48) && (keyCode <= 57)) || (keyCode == 13) || (keyCode == 46) || (keyCode == 45))){ 
			return false;
		}
	}else{
		if(!(((keyCode >= 48) && (keyCode <= 57)) || (keyCode == 13) || (keyCode == 46))){ 
			return false;
		}
	}
	var position = 0; 
	if (document.selection) {	//for IE8
		obj.focus();
		var sel = document.selection.createRange();
		position = obj.value.length - sel.text.length;
	}else{
		position = obj.selectionStart;
	}
	var ch=String.fromCharCode(keyCode);
	var value = obj.value.substring(0,position)+ch+obj.value.substring(position);//输入后的值
	var reg = /^\d+\.?\d{0,2}$/;
	if(canNegative != undefined && canNegative){//可以输入负数
		reg = /^(-)?\d+\.?\d{0,2}$/;
		if(value == "-"){
			return true;
		}
	}
	if(!(reg.test(value))){//验证只能输入两位小数
		return false;
	}
 }
function valDoubleNumber(obj,canNegative){
	var num = obj.value; 
	if(num.length > 0){
		if(num != "-" && isNaN(num)){
			$(obj).val("0.00").select();
			Public.tips({type: 2, content : '请输入数字！'});
			return false;
		}
		if(canNegative != undefined && canNegative){//可以输入负数
		}else{
			if(parseFloat(num) < 0){
				$(obj).val("0.00").select();
				Public.tips({type: 2, content : '请输入正数！'});
				return false;
			}
		}
	}
}

function listBillProcess(number,ar_type){
	var config = Public.getDefaultPage().CONFIG;
	$.dialog({ 
	   	id:'bill_approve_process',
	   	title:'单据审批流程',
	   	data:{'number':number,'ar_type':ar_type},
	   	max: false,
	   	min: false,
	   	lock:true,
	   	width:450,
	   	height:300,
	   	fixed:false,
	   	resize:false,
	   	content:'url:'+config.BASEPATH+'approve/to_list'
	});
}
function viewProductImg(pd_code){
	var config = Public.getDefaultPage().CONFIG;
	$.dialog({ 
		id: 'product_img',
		title: '商品图片',
		max: false,
		min: false,
		width: 400,
		height: 320,
		fixed:false,
		drag: true,
		content:'url:'+config.BASEPATH+'base/product/to_img_view/'+pd_code
	});
}
Public.checkDate = function(enddate){//1-已过期,2-即将过期
	if(enddate == null || enddate == ""){
		return 0;
	}
	var now = new Date().getTime();
	var endTime = new Date(enddate).getTime();
	if(endTime <= now){
		return 1;
	}
	var leftdays = (endTime - now)/(60 * 60 * 24 * 1000);
	if(leftdays <= 5){
		return 2;
	}
	return 0;
}